package com.wnxy.config;

import com.wnxy.listener.RedisListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;


    @Bean("redisJsonTemplate")
    public RedisTemplate<String, Object> createRedisTemplate(){
        RedisTemplate<String, Object> rt = new RedisTemplate<>();
        rt.setConnectionFactory(redisConnectionFactory);
        rt.setKeySerializer(RedisSerializer.string());
        rt.setHashKeySerializer(RedisSerializer.string());
        rt.setValueSerializer(RedisSerializer.json());
        rt.setHashValueSerializer(RedisSerializer.json());
        return rt;
    }
    @Bean
    RedisMessageListenerContainer redisMessageListenerContainer (RedisConnectionFactory redisConnectionFactory){
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        redisMessageListenerContainer.addMessageListener(new RedisListener(redisMessageListenerContainer), new PatternTopic("__keyevent@0__:expired"));
        return redisMessageListenerContainer;
    }

}
